<template>
  <div>
    <h3>成绩录入</h3>
    <div class="cultureScore">
      <el-form class="cultureScoreForm" inline-message ref="cultureScoreForm" :model="cultureScoreForm" :rules="rules" label-width="110px">
        <el-form-item label="学期">
          <span class="schoolTermName">{{this.dict_school_term[cultureScoreForm.schoolTermId]}}</span><br>
          <el-button-group>
            <el-button @click="cultureScoreForm.schoolTermId-=1" size="small">上一学期</el-button>
            <el-button @click="cultureScoreForm.schoolTermId+=1" size="small">下一学期</el-button>
            <el-button @click="cultureScoreForm.schoolTermId=currentSchoolTermId" size="small">回到当前学期</el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item label="考试类型" prop="resultTypeId">
          <el-radio-group v-model="cultureScoreForm.resultTypeId" size="small">
            <el-radio-button label="2">期中</el-radio-button>
            <el-radio-button label="3">期末</el-radio-button>
            <el-radio-button label="1">平时</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="运动项目">
          <el-select v-model="cultureScoreForm.sportId" @change="sportChange" filterable clearable style="width: 100%;" placeholder="请选择">
            <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运动小项">
          <el-select v-model="cultureScoreForm.sportItemId" @change="sportItemChange" filterable clearable style="width: 100%;" placeholder="请选择">
            <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in sportItemData" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运动员" prop="playerIdStr">
          <el-select v-model="cultureScoreForm.playerIdStr" multiple filterable clearable collapse-tags placeholder="请选择">
            <el-option :label="item.name" :value="item.playerId" v-for="(item,index) in playerData" :key="index"></el-option>
          </el-select>
          <el-button type="primary" @click='playerSelectAll'>全选</el-button>
        </el-form-item>
        <el-form-item label="科目" prop="subjectIdStr">
          <el-select v-model="cultureScoreForm.subjectIdStr" multiple filterable clearable collapse-tags placeholder="请选择">
            <el-option :label="item" :value="key" v-for="(item,key,index) in dict_subject" :key="index"></el-option>
          </el-select>
          <el-button type="primary" @click="cultureScoreForm.subjectIdStr = Object.keys(dict_subject)">全选</el-button>
        </el-form-item>
      </el-form>
      <div style="text-align: right;padding: 0 20px;">
        <el-button @click="go" :disabled="tableColumn.length!=0" size="small" type="primary" icon="el-icon-s-tools">批量录入</el-button>
        <el-button @click="tableColumn=[];dataList=[]" size="small" type="warning">清空</el-button>
      </div>
    </div>
    <div class="table">
      <vxe-toolbar>
        <template #buttons>
          <el-button type="success" icon="el-icon-download" size="small"  @click="exportDataAll">导出</el-button>
          <el-button type="success" icon="el-icon-printer" size="small"  @click="printEventAll">打印</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row  highlight-current-column
      :loading="loading" :data="dataList">
        <vxe-table-column
          v-for="(item,index) in tableColumn"
          :key="index"
          :type="item.type"
          :field="item.field"
          :title="item.title"
          :fixed="item.fixed"
          :min-width="item.width"
          :filters="item.filters">
          <template v-if="!item.field" #default="{ row }">
            <el-button @click="save(row)" type="primary" size="medium" icon="iconfont icon-save" circle></el-button>
          </template>
          <template v-else-if="item.mode=='input'" #default="{ row }">
            <el-input v-model="row[item.field]"></el-input>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-table v-show="false" resizable ref="XTable2" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row  highlight-current-column
      :loading="loading" :data="dataList">
        <vxe-table-column
          v-for="(item,index) in tableColumn"
          :key="index"
          :type="item.type"
          :field="item.field"
          :title="item.title"
          :fixed="item.fixed"
          :min-width="item.width"
          :filters="item.filters">
          <template v-if="!item.field" #default="{ row }">
            <el-button @click="save(row)" type="primary" size="medium" icon="iconfont icon-save" circle></el-button>
          </template>
          <template v-else-if="item.mode=='input'" #default="{ row }">
            <span>{{row[item.field]}}</span>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>
  </div>
</template>

<script>
  import {currentTerm,sport_item_by_sportId,get_player,orgSubject,result4coach,edu_examination_results} from "@/api/person.js"
  import {sport_by_org,sport_item} from "@/api/dict.js"
  export default {
    data() {
      return {
        dict_school_term: {},
        dict_sport: {},
        dict_sportItem: {},
        dict_player: {},
        dict_subject: {},
        cultureScoreForm: {
          schoolTermId: '',
          resultTypeId: '',
          sportId: '',
          sportItemId: '',
          playerIdStr: '',
          subjectIdStr: '',
        },
        sportItemData: [],
        playerData: [],
        currentSchoolTermId: '',
        rules: {
          resultTypeId: [{
            required: true,
            message: '请选择考试类型',
            trigger: 'change'
          }, ],
          playerIdStr: [{
            required: false,
            message: '请选择运动员',
            trigger: 'change'
          }, ],
          subjectIdStr: [{
            required: false,
            message: '请选择科目',
            trigger: 'change'
          }, ],
        },
        loading: false,
        dataList: [],
        tableColumn: [],
        print: true,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getCurrentTerm()
      })
    },
    methods: {
      exportDataAll() {
        if(this.dataList.length==0){
          this.$message.warning('数据为空！')
          return
        }
        this.$refs.XTable.exportData({
          filename: this.$store.state.user.org+'运动员'+this.$route.meta.title+this.dict_school_term[this.cultureScoreForm.schoolTermId],
          data: this.dataList
        })
      },
      printEventAll() {
        if(this.dataList.length==0){
          this.$message.warning('数据为空！')
          return
        }
        let topHtml = '<h2>'+this.dict_school_term[this.cultureScoreForm.schoolTermId]+'</h2>'
        this.$refs.XTable2.print({
          sheetName: this.dict_school_term[this.cultureScoreForm.schoolTermId],
          beforePrintMethod: ({
            content
          }) => {
            return topHtml + content
          }
        })
      },
      save(row) {
        let data = []
        this.cultureScoreForm.subjectIdStr.forEach(item=>{
          if(row[item]){
            data.push({
              playerId: row.playerId,
              resultTypeId: this.cultureScoreForm.resultTypeId,
              schoolTermId: this.cultureScoreForm.schoolTermId,
              score: row[item],
              studentId: -1,
              subjectId: item,
            })
          }
        })
        edu_examination_results(data).then(res=>{
          if(res.code === 200) {
            this.$message.success('保存成功！')
          }
        })
      },
      go() {
        this.rules.playerIdStr[0].required = true
        this.rules.subjectIdStr[0].required = true
        this.$refs.cultureScoreForm.validate((valid) => {
          if (valid) {
            let data = {}
            if(this.cultureScoreForm.schoolTermId) data.schoolTermId = this.cultureScoreForm.schoolTermId
            if(this.cultureScoreForm.resultTypeId) data.resultTypeId = this.cultureScoreForm.resultTypeId
            if(this.cultureScoreForm.playerIdStr) data.playerIdStr = this.cultureScoreForm.playerIdStr.join(',')
            if(this.cultureScoreForm.subjectIdStr) data.subjectIdStr = this.cultureScoreForm.subjectIdStr.join(',')
            this.loading = true
            result4coach(data).then(res=>{
              if(res.code === 200) {
                let tableData = []
                this.cultureScoreForm.playerIdStr.forEach(item=>{
                  let obj = {}
                  obj['playerName'] = this.dict_player[item]
                  obj['playerId'] = item
                    this.cultureScoreForm.subjectIdStr.forEach((item2,index2)=>{
                      this.tableColumn.push({
                        key: index2+1,
                        field: item2,
                        width: 100,
                        mode: 'input',
                        title: this.dict_subject[item2]
                      })
                      obj[item2] = ''
                    })
                    tableData.push(obj)
                })
                if(res.data.length!=0){
                  res.data.forEach(item=>{
                    tableData.forEach(item2=>{
                      if(item.playerId==item2.playerId){
                        item2[item.subjectId] = item.score
                      }
                    })
                  })
                }
                this.dataList = tableData
                this.tableColumn = this.deWeightThree(this.tableColumn)
                this.tableColumn.unshift({
                      field: 'playerName',
                      title: '姓名',
                      fixed: 'left',
                      width: 80,
                    })
                this.tableColumn.push({
                      field: '',
                      title: '操作',
                      fixed: 'right',
                      width: 55,
                    })
                 this.loading = false
              }else{
                this.$message.error(res.message)
              }
            })
          }else {
            return false;
          }
        })
      },
      deWeightThree(arr) {
        var temp = [];
        arr.forEach(function(a) {
            var check = temp.every(function(b) {
                return a.key !== b.key;
            })
            check ? temp.push(a) : ''
        })
        return temp;
      },
      playerSelectAll() {
        this.cultureScoreForm.playerIdStr = []
        this.playerData.forEach(item=>{
          this.cultureScoreForm.playerIdStr.push(item.playerId)
        })
      },
      sportChange() {
        this.cultureScoreForm.sportItemId = ''
        this.cultureScoreForm.playerIdStr = ''
        sport_item_by_sportId({
          sportId: this.cultureScoreForm.sportId
        }).then(res => {
          if (res.code === 200) {
            this.sportItemData = res.data
            this.get_player()
          }
        })
      },
      sportItemChange() {
        this.cultureScoreForm.playerIdStr = ''
        this.get_player()
      },
      get_player() {
        let data = {}
        if(this.cultureScoreForm.sportId) data.sportId = this.cultureScoreForm.sportId
        if(this.cultureScoreForm.sportItemId) data.sportItemId = this.cultureScoreForm.sportItemId
        get_player(data).then(res=>{
          this.playerData = res.data
          res.data.forEach(item=>{
            this.dict_player[item.playerId] = item.name
          })
        })
      },
      getCurrentTerm() {
        currentTerm().then(res=>{
          if(res.code === 200) {
            this.currentSchoolTermId = res.data.schoolTermId
            this.cultureScoreForm.schoolTermId = res.data.schoolTermId
          }
        })
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          this.dict_school_term = this.$store.state.user.dict_school_term
          sport_by_org().then(res => {
            this.dict_sport = res
          })
          sport_item().then(res => {
            this.dict_sportItem = res
          })
          orgSubject().then(res => {
            res.data.forEach(item=>{
              this.dict_subject[item.subjectId] = item.alias
            })
          })
          resolve()
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .cultureScore{
    width: 100%;
    background-color: #FFFFFF;
    padding: 20px 0 20px 30%;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    .cultureScoreForm{
      width: 500px;

      .schoolTermName{
        font-size: 120%;
        font-weight: bold;
      }
    }
  }
  .table{
    width: 100%;
  }
</style>
